package com.example.yilanchatserver.application.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.example.yilanchatserver.business.freechat.*;
import com.example.yilanchatserver.business.freechat.service.RedisService;
import com.example.yilanchatserver.business.freechat.service.UtopiaService;
import com.example.yilanchatserver.business.freechat.service.ZhiPuService;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatDTO;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatInputDTO;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatPromptDTO;
import com.example.yilanchatserver.business.freechat.service.dto.UtopiaStreamDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;

@ServerEndpoint(value = "/metah/freechat/utopia/stream")
@Component
@Slf4j
public class UtopiaWebSocketServer {
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<UtopiaWebSocketServer> webSocketSet = new CopyOnWriteArraySet<UtopiaWebSocketServer>();



    private static UtopiaService utopiaService;

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;


    private static RedisService redisService;

    //    public ChatGPTWebSocketServer_metah(){
//        this.chatGPTService = SpringUtil.getBean(ChatGPTService.class);
//    }
    @Resource
    private void setChatGPTService(UtopiaService utopiaService){
        UtopiaWebSocketServer.utopiaService = utopiaService;

    }

    @Resource
    private void setRedisService(RedisService redisService){
        UtopiaWebSocketServer.redisService = redisService;
    }


    private static String tokenKey = "wudao:token";

    private static String API_KEY = "b54183298cd44d3e9391c3426e70a7fe";



    // 用户PUBLIC KEY（请登录开放平台获取 https://maas.aminer.cn ）

    private static String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIMuLoUbpKWDdrj8/sniPR2u37D5gJFfBzBQCLNAKJb9MwelEGmGeUotU2XMEdqk7Uq4tBzOmaOudFeXgc02J90CAwEAAQ==";




    private static String AUTH_TOKEN_URL = "https://maas.aminer.cn/api/paas/passApiToken/createApiToken";

    private String getToken() throws Exception {
        try {
            String token = redisService.get(tokenKey);
            if(StringUtils.isEmpty(token)){
                Map<String, Object> resultMap = WuDaoUtils.getToken(AUTH_TOKEN_URL, API_KEY, PUBLIC_KEY);
                int code = (int) resultMap.get("code");
                if (code == 200) {
                    token = String.valueOf(resultMap.get("data"));
                    redisService.set(tokenKey, token, 8, TimeUnit.HOURS);
                }
                else {
                    throw new BusinessException(BusinessErrorCodes.DEFAULT_BUSINESS_ERROR);
                }
            }
            return token;
        } catch (Exception e) {
            log.error("获取token失败", e);
            throw e;
        }
//        return null;
    }



    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this); //加入set中
        addOnlineCount(); //在线数加1
        int cnt = 0;

    }

    /**
     * 图片转base64字符串
     *
     * @param imgFile 图片路径
     * @return
     */
    public static String imageToBase64Str(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); //从set中删除
        subOnlineCount(); //在线数减1

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param inputQuestion 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String inputQuestion, Session session) throws Exception {

        for (UtopiaWebSocketServer item : webSocketSet) {
            if(item.session!=session){
                continue;
            }
            Flux<String> response;

            UtopiaStreamDTO freeChatDTO = JSON.parseObject(inputQuestion, UtopiaStreamDTO.class);
            response = utopiaService.send(freeChatDTO);



            response.subscribe(message -> {
                try {

                    if(!"[Done]".equals(message) && !"[Error]".equals(message)){
                        item.sendMessage(BaseResponseEntity.SUCCESS(message));
                        TimeUnit.MILLISECONDS.sleep(20);
                    }
                    else if("[Done]".equals(message)){
                        item.sendMessage(BaseResponseEntity.FINISH());
                        item.closeSession();
                    }
                    else{
                        item.sendMessage(BaseResponseEntity.ERROR());
                        item.closeSession();
                    }
                } catch (Exception e) {
                    try {
                        item.closeSession();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            });

//            item.closeSession();
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        error.printStackTrace();
    }

    public void closeSession() throws IOException {
        this.session.close();
    }

    public void sendMessage(BaseResponseEntity baseResponseEntity) throws IOException {
        String message = JSON.toJSONString(baseResponseEntity);
        if(this.session.isOpen()){
            this.session.getBasicRemote().sendText(message);
        }
        else{
            webSocketSet.remove(this);
        }

    }


    /**
     * 群发自定义消息
     * */


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        UtopiaWebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        UtopiaWebSocketServer.onlineCount--;
    }
}
